package com.chuangjiangx.member.basic.web.interceptor;

import com.chuangjiangx.commons.CurrentThreadContext;
import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.commons.response.GenericResponse;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.member.basic.web.redis.SessionService;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * token拦截器
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private SessionService loginService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisTemplate redisTemplate;

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//
//        if (handler instanceof HandlerMethod) {
//            HandlerMethod method = (HandlerMethod) handler;
//            Login login = method.getMethodAnnotation(Login.class);
//            if (login != null) {
//                String tokenStr = null;
//                MbrUserContext loginInfo = null;
//                try {
//                    tokenStr = request.getHeader("token");
//                    if(StringUtils.isBlank(tokenStr)){
//                        tokenStr = request.getParameter("token");
//                    }
//                    String jsonStr = redisTemplate.opsForValue().get(tokenStr);
//                    loginInfo = JacksonUtils.toObject(objectMapper,jsonStr,MbrUserContext.class);
//                } catch (Exception e) {
//                    log.warn("{}",e);
//                    return printError(response, "未登录");
//                }
//                if(StringUtils.isBlank(loginInfo.getMobile())){
//                    //token对象中没有手机号码也算没登录
//                    return printError(response, "未登录");
//                }
//
//                //在当前线程中存储 Token 对象
//                CurrentThreadContext.setCurrentUser(loginInfo);
//
//            }
//        }
//        return true;
//    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            MbrUserContext userContext = loginService.currentUserContext();
            //在当前线程中存储 Token 对象
            CurrentThreadContext.setCurrentUser(userContext);
            Login login = method.getMethodAnnotation(Login.class);
            if (login != null) {
                if(userContext == null || StringUtils.isBlank(userContext.getMobile())){
                    return printError(response, "未登录");
                }

            }
        }
        return true;
    }
    /**
     * 未登录抛异常
     */
    private Boolean printError(HttpServletResponse response, String errMsg) throws Exception {
        Response resp = GenericResponse.failure("000006",errMsg);
        response.setHeader("content-type","application/json;charset=utf-8");
        response.getWriter().println(JacksonUtils.toJson(objectMapper,resp));
        return false;
    }
}
